package com.lindroy.androidplayer.ui.search

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.flexbox.*
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.databinding.FragmentSearchBinding
import com.lindroy.androidplayer.utils.navigator.SmoothNavHostFragment
import com.lindroy.androidplayer.viewmodels.SearchViewModel
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.collectWhenResumed
import com.lindroy.lib_utils.extensions.hideKeyboard
import com.lindroy.lib_utils.extensions.shortToast

/**
 * @author Lin
 * @date 2022/3/8
 * @function
 */
class SearchFragment : BaseLazyFragment<FragmentSearchBinding>() {

    private val navController by lazy {
        (childFragmentManager.findFragmentById(R.id.nav_host_search) as SmoothNavHostFragment).navController
    }

    private val viewModel by activityViewModels<SearchViewModel>()

    override fun FragmentSearchBinding.initView(savedInstanceState: Bundle?) {
        vm = viewModel

    }

    override fun FragmentSearchBinding.initListener() {
        viewModel.startSearchListener.collectWhenResumed(viewLifecycleOwner) {
            SearchResultFragment.start(navController, it.orEmpty())
            ivSend.hideKeyboard()
        }

        viewModel.backClickListener.observe(viewLifecycleOwner) {
            findNavController().navigateUp()
        }

        viewModel.keyword.observe(viewLifecycleOwner) {
            if (it.isNullOrBlank() && navController.currentDestination?.id != R.id.searchHotKeyFragment) {
                navController.navigateUp()
            }
        }
    }

    override fun lazyLoad() {
    }
}